#include "User_SPI.h"

extern 	SPI_HandleTypeDef hspi1;
const u8 HC165_CS_NUM = 9;
const u8 HC165_NUM = 64;

u8 HC165_Input_Dat[HC165_CS_NUM];
//u8 HC165_Input_Dat_Cpy[HC165_NUM];

void HC165_Read()
{   
	SPI_HandleTypeDef* spiHandle;
	spiHandle = &hspi1;

	GPIO_SetBits(HC165_PL_PORT, HC165_PL_PIN);
	

	spiHandle->pRxBuffPtr = (uint8_t*) HC165_Input_Dat;
    spiHandle->RxXferCount = HC165_CS_NUM+1;
    __HAL_SPI_ENABLE(spiHandle);
    while (spiHandle->RxXferCount > 0U)
    {
        if (__HAL_SPI_GET_FLAG(spiHandle, SPI_FLAG_RXNE))
        {
            /* read the received data */
            (*(uint8_t*) spiHandle->pRxBuffPtr) = *(__IO uint8_t*) &spiHandle->Instance->DR;
            spiHandle->pRxBuffPtr += sizeof(uint8_t);
            spiHandle->RxXferCount--;
        }
    }
    __HAL_SPI_DISABLE(spiHandle);
	GPIO_ResetBits(HC165_PL_PORT, HC165_PL_PIN);
}

u8 HC165_Get_Bit(u8 n)
{
	u8 ret = 1;
	u8 cs;
	u8 offset;
	u8 dat;
	if(n >= HC165_NUM)
	{
		return ret;
	}
	cs = n/8;
	offset = n%8;
	if(cs < HC165_CS_NUM-1)
	{
		cs += 1;
		dat = HC165_Input_Dat[cs];
		if(((dat>>(7-offset))%2)==0)
		{
			ret = 0;
		}
	}
	
	return ret;
}
